package com.hxzy.common.util;

import com.hxzy.common.TZXMConst;
import com.hxzy.entity.system.SysDictData;
import com.hxzy.service.system.SysDictDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 通用字典管理工具类(数据库值同步到redis中，清空redis中的值)
 */
@Component
public class DictDataUtil {

    @Autowired
    private SysDictDataService sysDictDataService;

    @Autowired
    private RedisTemplate redisTemplate;

    @PostConstruct
    public void initData(){
        this.loadDataToRedis();
    }

    /**
     * 加所有通用字典到redis缓存中
     */
    public void loadDataToRedis(){
        List<SysDictData> allData = this.sysDictDataService.findAll();
        //希望它来分组
        Map<String, List<SysDictData>> groupByData = allData.stream().collect(Collectors.groupingBy(SysDictData::getDictType));

        for(String key :groupByData.keySet()){
            String redisKey=getRedisKey(key.trim());
            List<SysDictData>  redisValue=groupByData.get(key);
            redisTemplate.opsForValue().set(redisKey,redisValue);
        }
    }


    /**
     * 得到redisKey
     * @param dictTypeName
     * @return
     */
    private String getRedisKey(String dictTypeName){
        return TZXMConst.DICT_DATA_KEY+dictTypeName;
    }


    /**
     * 获取缓存中的值
     * @param dictTypeName
     * @return
     */
    public List<SysDictData> getDataByDictType(String dictTypeName){
        String redisKey=this.getRedisKey(dictTypeName);
        return (List<SysDictData>) this.redisTemplate.opsForValue().get(redisKey);
    }

    /**
     * 根据键，清空所有的缓存数据
     * @param dictTypeName
     */
    public void clearCacheByDictType(String dictTypeName){
        String redisKey=this.getRedisKey(dictTypeName);
        this.redisTemplate.delete(redisKey);
    }

    /**
     * 清空所有的通用数据字典的缓存数据
     */
    public void clearAllDictDataCache(){
        Set keys = this.redisTemplate.keys(TZXMConst.DICT_DATA_KEY + "*");
        for(Object key :keys){
            String redisKey=key.toString();
            this.redisTemplate.delete(redisKey);
        }
    }

    /**
     * 刷新缓存(重新加载数据)
     */
    public void refreshCache(){
        this.clearAllDictDataCache();
        this.loadDataToRedis();
    }

    /**
     * 同步指定的dictType的缓存
     * @param dictTypeName
     */
    public void refreshCacheByDictTypeName(String dictTypeName){
        String redisKey=this.getRedisKey(dictTypeName);
        //查询数据库的值
        List<SysDictData> dictData=this.sysDictDataService.selectByDictTypeName(dictTypeName);
        this.redisTemplate.opsForValue().set(redisKey, dictData);
    }

}
